package com.ljc.cjgl.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ljc.cjgl.entitiy.Course;
import com.ljc.cjgl.form.CourseForm;
import com.ljc.cjgl.repository.CourseRepository;

@Service
public class CourseService {
	@Autowired
	private CourseRepository courseDAO;
	
	public List<Course> findAll(){
		return courseDAO.findAll();
	}
	
	public Course findById(Integer id) {
		Optional<Course> optional = courseDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}

	public Page<Course> findAll(Specification<Course> specification, PageRequest pageRequest) {
		return courseDAO.findAll(specification, pageRequest);
	}

	
	public synchronized boolean save(CourseForm form) {
		Course model=new Course();
		if(form.getId()!=null) {
			model=findById(form.getId());
		}
		try {
			BeanUtils.copyProperties(form, model,"id");
			courseDAO.save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	
	public synchronized boolean delete(List<Course> courses) {
		try {
			for (Course course : courses) {
				courseDAO.deleteById(course.getId());
			}
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	
	
}
